package com.project;

import com.project.config.WebMvcConfig;
import com.project.filter.*;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Filter;
import javax.servlet.ServletContext;

/**
 * @author lyl
 * description:
 */
public class Bootloader {
    public static void main(String[] args) {
        new Bootloader();
    }

    public Bootloader() {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8088);
        tomcat.getConnector();
        Context context = tomcat.addContext("", null);
        //所有请求进行拦截
        this.registerFilter(context, new CharFilter(), "/*");
        //部分请求进行拦截
        this.registerFilter(context, new CustomLoginFilter(), "/html/custom/*");
        this.registerFilter(context, new ManagerLoginFilter(), "/html/manager/*");
        this.registerFilter(context, new SendLoginFilter(), "/html/send/*");
        this.registerFilter(context, new OwnerLoginFilter(), "/html/owner/*");
        WebApplicationContext wac = createApplicationContext(context.getServletContext());
        //创建前端控制器对象
        DispatcherServlet ds = new DispatcherServlet(wac);
        Wrapper wa = Tomcat.addServlet(context, "ds", ds);
        wa.setLoadOnStartup(0);
        wa.addMapping("/*");
        try {
            tomcat.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建SpringMvc的应用上下文
     *
     * @param servletContext
     * @return
     */
    public static WebApplicationContext createApplicationContext(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebMvcConfig.class);
        ctx.setServletContext(servletContext);
        ctx.refresh();
        ctx.registerShutdownHook();
        return ctx;
    }

    /**
     * 进行过滤器注册
     *
     * @param context     上下文
     * @param filter      过滤器
     * @param filterScope 过滤器范围
     */
    private void registerFilter(Context context, Filter filter, String filterScope) {
        FilterDef def = new FilterDef();
        def.setFilterName(filter.getClass().getName());
        def.setFilter(filter);

        FilterMap fm = new FilterMap();
        fm.setFilterName(filter.getClass().getName());
        fm.addURLPattern(filterScope);

        context.addFilterDef(def);
        context.addFilterMap(fm);

    }


}
